import type { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

import { queryRefreshToken } from '@/api/login'
import { removeRefreshToken, removeToken } from '@/utils/auth'

/**
 * @description 判断是否为刷新token请求
 * @param config
 * @returns
 */
export const isRefreshRequest = (config: AxiosRequestConfig) => {
  return !!config.__isRefreshRequest
}

/**
 * @description 存储刷新token请求的promise
 */
let refreshPromise: Promise<boolean> | null

/**
 * @description 刷新token
 * @returns
 */
export const refreshToken = () => {
  if (refreshPromise) {
    return refreshPromise
  }
  refreshPromise = new Promise((resolve) => {
    queryRefreshToken()
      .then(() => {
        resolve(true)
      })
      .catch((error: any) => {
        ElMessage.error(error?.msg)
        removeToken()
        removeRefreshToken()
        resolve(false)
      })
  })

  refreshPromise.finally(() => {
    refreshPromise = null
  })
  return refreshPromise
}
